//
//  BTEAddressManager.swift
//  BTE
//
//  Created by Mike Zhang on 2025/9/1.
//


import UIKit
import FMDB
import SmartCodable



class BTEAddressManager {
    
    static let stand = BTEAddressManager()
    
    private var database: FMDatabase!
    
    private let service = BTEProductToolNetServer()

    func loadAddress(){
        service.decompensates { model in
            switch model {
            case .success(let success):
                (success?.sidelingwise ?? []).forEach {[weak self] item in
                    self?.restroaddress(item)
                }
                break
            case .failure(let failure):
                break
            }
        }
    }
    
    init() {
        let url = try! FileManager.default.url(for: .documentDirectory,
                                               in: .userDomainMask,
                                               appropriateFor: nil,
                                               create: false)
            .appendingPathComponent(addressSQL)
        database = FMDatabase(path: url.relativePath)
        database.open()
        createTable()
    }
    
    deinit {
        database?.close()
    }
    
    let a1 = "geothermally"
    let a2 = "remoted"
    let a3 = "manificum"

    private func createTable() {
        let createTableSQL = """
        CREATE TABLE IF NOT EXISTS addres111 (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
                            geothermally TEXT,
                remoted TEXT,
                manificum TEXT,
            parent_id INTEGER,
            choised INTEGER
        );
        """
        do {
            try database.executeUpdate(createTableSQL, values: nil)
        } catch {
            print("Failed to create table: \(error.localizedDescription)")
        }
    }
  
    
        func restroaddress(_ model: BTECarneolfejubdaderesswgeNetModel, parentId: Int? = nil) {
            guard !isfollowedModelsExist(model, parentId: parentId) else {
                       return
                   }
            do {
                try database.beginTransaction()
                
                try database.executeUpdate("INSERT INTO addres111 (\(a1), \(a2), \(a3), parent_id, choised) VALUES (?, ?, ?, ?, ?)", values: [
                    model.geothermally ?? "",
                    model.remoted ?? "",
                    model.manificum ?? "",
                    parentId ?? NSNull(),
                    model.choised ? 1 : 0
                ])
    
                let lastInsertId = Int(database.lastInsertRowId)
    
                if let children = model.flinter {
                    for child in children {
                        
                        restroaddress(child, parentId: lastInsertId)
                    }
                }
               
                try database.commit()
    
            } catch {
                database.rollback()
                print("zw: \(error.localizedDescription)")
            }
        }
    

    private func isfollowedModelsExist(_ model: BTECarneolfejubdaderesswgeNetModel, parentId: Int?) -> Bool {
        var exists = false
        do {
            
            let query = "SELECT COUNT(*) FROM addres111 WHERE \(a1) = ? AND \(a2) = ? AND \(a3) = ? AND parent_id IS ?"
            let rs = try database.executeQuery(query, values: [
                model.geothermally ?? "",
                model.remoted ?? "",
                model.manificum ?? "",
                parentId ?? NSNull()
            ])
            if rs.next() {
                exists = rs.int(forColumnIndex: 0) > 0
            }
        } catch {
            print("\(error.localizedDescription)")
            
        }
        return exists
    }
    
    func loadfollowedModels(from parentId: Int? = nil) -> [BTECarneolfejubdaderesswgeNetModel] {
        var model = [BTECarneolfejubdaderesswgeNetModel]()
        do {
            let rs = try database.executeQuery("SELECT * FROM addres111 WHERE parent_id IS ?", values: [parentId ?? NSNull()])
            while rs.next() {
                let models = BTECarneolfejubdaderesswgeNetModel()
                models.geothermally = rs.string(forColumn: "\(a1)")
                models.remoted = rs.string(forColumn: "\(a2)")
                models.manificum = rs.string(forColumn: "\(a3)")
                models.choised = rs.bool(forColumn: "choised")
                let id = Int(rs.int(forColumn: "id"))
                models.flinter = loadfollowedModels(from: id)
                model.append(models)
            }
        } catch {
            print("\(error.localizedDescription)")
        }
        return model
    }
    
    
    
    static func fewfewf222few(from lookingString: String, in model: [BTECarneolfejubdaderesswgeNetModel]?) -> (index1: Int, index2: Int, index3: Int)? {
        let lookingComponents = lookingString.split(separator: "|").map { String($0) }
        guard lookingComponents.count == 3 else { return nil }
        
        guard let level1 = model else { return nil }
        
        if let index1 = level1.firstIndex(where: { $0.manificum == lookingComponents[0] }) {
            let level1Flawd = level1[index1]
            
            if let level2 = level1Flawd.flinter,
               let index2 = level2.firstIndex(where: { $0.manificum == lookingComponents[1] }) {
                let level2Flawd = level2[index2]
                
                if let level3 = level2Flawd.flinter,
                   let index3 = level3.firstIndex(where: { $0.manificum == lookingComponents[2] }) {
                    return (index1, index2, index3)
                }
            }
        }
        
        return nil
    }

    static func lookingaddress(model: [BTECarneolfejubdaderesswgeNetModel]?, index1: Int, index2: Int, index3: Int) -> String? {
        guard let level1 = model, level1.indices.contains(index1) else {
            return nil
        }
        
        let level1Flawd = level1[index1]
        guard let level2 = level1Flawd.flinter, level2.indices.contains(index2) else {
            return nil
        }
        
        let level2Flawd = level2[index2]
        guard let level3 = level2Flawd.flinter, level3.indices.contains(index3) else {
            return nil
        }
        
        let level3Flawd = level3[index3]
        
        let lookingValues = [
            level1Flawd.manificum ?? "",
            level2Flawd.manificum ?? "",
            level3Flawd.manificum ?? ""
        ]
        
        return lookingValues.joined(separator: "|")
    }
    

    static func level1fewfwbrgew(model: [BTECarneolfejubdaderesswgeNetModel]?, index1: Int, index2: Int, index3: Int) -> (level1Looking: String?, level2Looking: String?, level3Looking: String?)? {
        guard let level1 = model, level1.indices.contains(index1) else {
            return nil
        }
        
        let level1Flawd = level1[index1]
        guard let level2 = level1Flawd.flinter, level2.indices.contains(index2) else {
            return nil
        }
        
        let level2Flawd = level2[index2]
        guard let level3 = level2Flawd.flinter, level3.indices.contains(index3) else {
            return nil
        }
        
        let level3Flawd = level3[index3]
        
        return (level1Flawd.manificum, level2Flawd.manificum, level3Flawd.manificum)
    }


}



let addressSQL = "addressSQL.sqlite"
